package com.microstation.controller.system;

import com.microstation.common.Assist;
import com.microstation.common.Result;
import com.microstation.entity.po.MenuInfo;
import com.microstation.entity.po.RoleInfo;
import com.microstation.enums.ResultEnum;
import com.microstation.exception.RecordHaveException;
import com.microstation.service.MenuInfoService;
import com.microstation.service.RoleInfoService;
import com.microstation.util.RightsHelper;
import com.microstation.util.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigInteger;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author XuCong
 * @date 2018-02-15
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    private final static byte[] lock = new byte[0]; // 特殊的instance变量
    private final static Logger logger = LoggerFactory.getLogger(AuthController.class);
    @Autowired
    private RoleInfoService roleInfoService;
    @Autowired
    private MenuInfoService menuInfoService;

    @RequestMapping(value = "/listRoles", method = RequestMethod.POST)
    public Result listRoles(@RequestParam(name = "key", required = false) String key,
                            @RequestParam(name = "pageIndex", required = true, defaultValue = "0") Integer pageIndex,
                            @RequestParam(name = "limit", required = true, defaultValue = "10") Integer limit) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Assist assist = new Assist();
            if (StringUtil.isNotEmpty(key)) {
                assist.andLike("role_name", StringUtil.formatLike(key));
            }
            assist.setRowSize(limit);
            assist.setPage(pageIndex + 1);
            Result result = roleInfoService.find(assist);
            return new Result(result.getResults(), result.getRows());
        } catch (Exception e) {
            return new Result(Boolean.TRUE, ResultEnum.ERROR.getInfo(), 0L);
        }
    }


    @RequestMapping(value = "/saveRole", method = RequestMethod.POST)
    public Result saveRole(RoleInfo roleInfo) {
        try {
            if (StringUtil.isEmpty(roleInfo.getRoleName())) {
                return new Result(true, ResultEnum.EMPTY.getType(), "请输入角色名", null);
            }
            roleInfo.setGmtCreate(Calendar.getInstance().getTime());
            roleInfo.setGmtModified(roleInfo.getGmtCreate());
            return roleInfoService.saveRole(roleInfo);
        } catch (RecordHaveException e) {
            return new Result(true, ResultEnum.FAIL.getType(), e.getMessage(), null);
        } catch (Exception e) {
            logger.info(ResultEnum.ERROR.getType(), e);
            return new Result(true, ResultEnum.ERROR.getType(), ResultEnum.ERROR.getInfo(), null);
        }
    }

    @RequestMapping(value = "/updateRole", method = RequestMethod.POST)
    public Result updateRole(@RequestParam(name = "id", required = true) Long id, String roleName) {
        try {
            if (StringUtil.isEmpty(roleName)) {
                return new Result(true, ResultEnum.EMPTY.getType(), "请输入角色名", null);
            }
            RoleInfo roleInfo = roleInfoService.findOne(id);
            if (roleInfo == null) {
                return new Result(true, ResultEnum.NORECORD.getType(), ResultEnum.NORECORD.getInfo(), null);
            }
            roleInfo.setRoleName(roleName);
            RoleInfo param = new RoleInfo();
            param.setId(roleInfo.getId());
            param.setRoleName(roleInfo.getRoleName());
            return roleInfoService.updateRoleInfo(param);
        } catch (Exception e) {
            logger.info(ResultEnum.ERROR.getType(), e);
            return new Result(true, ResultEnum.ERROR.getType(), ResultEnum.ERROR.getInfo(), null);
        }
    }

    @RequestMapping(value = "/removeRole", method = RequestMethod.POST)
    public Result removeRole(@RequestParam(name = "ids", required = true) String ids) {
        try {
            return roleInfoService.removeRole(ids);
        } catch (Exception e) {
            logger.info(ResultEnum.ERROR.getType(), e);
            return new Result(true, ResultEnum.ERROR.getType(), ResultEnum.ERROR.getInfo(), null);
        }
    }


    @RequestMapping(value = "/loadAuth", method = RequestMethod.POST)
    public Result loadAuth(@RequestParam(name = "roleId", required = true) Long roleId) throws Exception {
        JSONObject jsonObject = null;
        JSONArray jsonArray = null;
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setExcludes(new String[]{"menuId", "menuUrl", "menuFlag", "menuDesc", "sort", "gmtCreate",
                "gmtModified"});
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            RoleInfo roleInfo = roleInfoService.findOne(roleId);
            Assist assist = new Assist();
            List<MenuInfo> menuInfoList = menuInfoService.listByAssist(assist);
            for (MenuInfo menuInfo : menuInfoList) {
                menuInfo.setHasMenu(RightsHelper.testRights(roleInfo.getRoleRights(), "" + menuInfo.getId()));
            }
            jsonArray = JSONArray.fromObject(menuInfoList, jsonConfig);
            String json = jsonArray.toString();
            json = json.replace("parentId", "pId").replace("menuName", "name").replace("hasMenu",
                    "checked");
            return new Result(false, ResultEnum.SUCCESS.getType(), json);
        } catch (Exception e) {
            logger.info(ResultEnum.ERROR.getType(), e);
            return new Result(true, ResultEnum.ERROR.getType(), ResultEnum.ERROR.getInfo(), null);
        }
    }

    @RequestMapping(value = "/updAuth", method = RequestMethod.POST)
    public Result updAuth(@RequestParam(name = "id", required = true) Long roleId,
                          @RequestParam(name = "ids", required = true, defaultValue = "1") String ids) {
        try {
            RoleInfo roleInfo = roleInfoService.findOne(roleId);
            if (roleInfo == null) {
                return new Result(true, ResultEnum.NORECORD.getType(), ResultEnum.NORECORD.getInfo(), null);
            }
            BigInteger rights = RightsHelper.sumRights(ids.split(","));
            roleInfo.setRoleRights(rights.toString());
            RoleInfo param = new RoleInfo();
            param.setId(roleInfo.getId());
            param.setRoleRights(roleInfo.getRoleRights());
            roleInfoService.updateNotNullById(param);
            return new Result(false, ResultEnum.SUCCESS.getType(), ResultEnum.SUCCESS.getInfo(), null);
        } catch (Exception e) {
            logger.info(ResultEnum.ERROR.getType(), e);
            return new Result(true, ResultEnum.ERROR.getType(), ResultEnum.ERROR.getInfo(), null);
        }
    }
}
